import fs from 'fs'
import { formatToHump } from './utils.js'

export const createRestful = (tableName) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    const config = JSON.parse(data)
    const requestPrefix = config.restful.prefix
    const humpTableName = formatToHump(tableName)
    const folder = `${config.vendorFolder}/${humpTableName}`
    // verify file is exist or not
    const fileName = `${folder}/restful.ts`
    if (fs.existsSync(fileName)) {
      // file is exist
      console.log(`======file is exist and ignore to created restful:${tableName}=======`)
    } else {
      // file is not exist
      if (!fs.existsSync(folder)) {
        fs.mkdirSync(folder, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      const content = getRestfulTmeplate(config, tableName, requestPrefix)
      fs.writeFile(fileName, content, { flag: 'a' }, (err) => {
        if (err) {
          console.log('========error======')
          throw err
        } else {
          console.log(`======succeessfully created model:${tableName}=======`)
        }
      })
    }
  })
}
const getRestfulTmeplate = (config, tableName, requestPrefix = '') => {
  const humpTableName = formatToHump(tableName)
  const folder = `${config.vendorFolder}/${humpTableName}`
  // verify file is exist or not
  const fileName = `${folder}/restful.ts`

  if (fs.existsSync(fileName)) {
    // file is exist
    console.log(`======file is exist and ignore to created restful:${tableName}=======`)
  } else {
    const path = config.http.folder.replace(/..\//, '') === '' ? '' : '/' + config.http.folder.replace(/..\//, '')
    return `import http from '@${path}/http'
import { Form } from './form'
export const add = (req:Form) => {
  return http.fetchPost('${requestPrefix}/${tableName}/add', req)
}
export const del = (${tableName}_id:number) => {
  return http.fetchPost('${requestPrefix}/${tableName}/del',{${tableName}_id})
}
export const update = (req:Form) => {
  return http.fetchPost('${requestPrefix}/${tableName}/update', req)
}
export const get = (${tableName}_id:number) => {
  return http.fetchPost('${requestPrefix}/${tableName}/get' ,{${tableName}_id})
}
export const list = (filter:any) => {
  return http.fetchPost('${requestPrefix}/${tableName}/list', filter)
}
  `
  }
}
